import { getToken } from '@/utils/auth'
import { ElNotification } from 'element-plus'
import axios from 'axios'
import get from 'lodash/get'

//文件下载
export default async ({url, params,fileName },) => {
  try {
    const res = await axios.request({
      method: 'get',
      params,
      responseType: "blob",
      url,
      headers: {
        Accept: "application/json",
        Authorization: `Bearer ${getToken()}`,
        "Content-Type": "application/json; charset=utf-8;",
        withCredentials: true,
      },
    });
    if (res.data.type !== "application/json") {
      return convertRes2Blob(res,fileName);
    } else {
      const enc = new TextDecoder('utf-8');
      res.data.arrayBuffer().then(buffer => {
        const data = JSON.parse(enc.decode(new Uint8Array(buffer))) || {};
        console.log(data)
        ElNotification({
          type: "error",
          title: data.msg,
          duration: 1000
        })
      })
    }
  } catch (err) {
    console.error(err);
  }
};

/**
 * Promise转化Blob类型
 * @param {response} axios返回的Promise 
 */
function convertRes2Blob(response,fileName) {
  // 提取文件名
//   const fileName = decodeURI(get(response.headers['content-disposition'].match(
//     /filename\*=(.*)/
//   ), '1', '')).split("''")[1]
  // 将二进制流转为blob
  const blob = new Blob([response.data], { type: 'application/octet-stream' })
  if (typeof window.navigator.msSaveBlob !== 'undefined') {
    // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
    window.navigator.msSaveBlob(blob, fileName)
  } else {
    // 创建新的URL并指向File对象或者Blob对象的地址
    const blobURL = window.URL.createObjectURL(blob)
    // 创建a标签，用于跳转至下载链接
    const tempLink = document.createElement('a')
    tempLink.style.display = 'none'
    tempLink.href = blobURL
    tempLink.setAttribute('download', fileName)
    // 兼容：某些浏览器不支持HTML5的download属性
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank')
    }
    // 挂载a标签
    document.body.appendChild(tempLink)
    tempLink.click()
    document.body.removeChild(tempLink)
    // 释放blob URL地址
    window.URL.revokeObjectURL(blobURL)
  }
}
